<template>
  <div class="main-todo">
    <input type="text" class="add-todo" placeholder="what to do?" autofocus v-model="content" @keyup.enter="addTodo" />
    <todo-item @changeTodo="changeTodo" @clearTodo="clearTodo" v-for="todo in todoList" :key="todo.id" :todo="todo"></todo-item>
    <todo-info @handleNav="handleNav" @clearAll="clearAll" :total="todoList.length"></todo-info>
  </div>
</template>

<script>
import TodoInfo from './coms/TodoInfo.vue'
import TodoItem from './coms/TodoItem.vue'
export default {
  components: { TodoItem, TodoInfo },
  name: 'MainTodo',
  data() {
    return {
      content: '',
      todoData: [],
      nav: '', //状态
    }
  },
  computed: {
    todoList() {
      switch (this.nav) {
        case 'all':
          return this.todoData
        case 'active':
          return this.todoData.filter((todo) => todo.checked)
        case 'completed':
          return this.todoData.filter((todo) => !todo.checked)
        default:
          return this.todoData
      }
    },
  },
  created() {},
  methods: {
    addTodo() {
      const { content, todoData } = this
      if (!content.trim()) return
      const todo = {
        id: Math.random() * Math.random(),
        checked: false,
        content,
      }
      todoData.unshift(todo)
      this.content = ''
    },
    // 选择todo
    changeTodo(todo) {
      const istodo = this.todoData.find((td) => td.id === todo.id)
      istodo.checked = !istodo.checked
    },
    // 删除todo
    clearTodo(todo) {
      const index = this.todoData.findIndex((td) => td.id === todo.id)
      this.todoData.splice(index, 1)
    },
    // 状态筛选
    handleNav(nav) {
      this.nav = nav
    },
    // 清除全部
    clearAll() {
      this.todoData = []
    },
  },
}
</script>

<style lang="stylus" scoped>
.main-todo
  margin: 0 auto
  width: 600px
  background: #fff
  box-shadow: 0 0 5px #666

  .add-todo
    padding: 16px 16px 16px 36px
    font-size: 24px
    font-weight: inherit
    color: inherit
    width: 100%
    border: none
    outline: none
    box-sizing: border-box
</style>